package com.atguigu.gulimail.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimail.member.vo.MemberLoginVo;
import com.atguigu.gulimail.member.vo.MemberRegistVo;
import com.atguigu.gulimail.member.vo.SocialUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimail.member.dao.MemberDao;
import com.atguigu.gulimail.member.entity.MemberEntity;
import com.atguigu.gulimail.member.service.MemberService;
import org.springframework.util.DigestUtils;

@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R saveRegist(MemberRegistVo registVo) {
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setLevelId(1L);//会员等级默认为id= 1：普通会员
        if(chickUserNamenique(registVo.getUserName())){
            memberEntity.setUsername(registVo.getUserName());//设置用户名
        }else{
            return R.error(15001,"该用户名已存在");
        }
        if (chickPhoneUnique(registVo.getPhone())){
            memberEntity.setMobile(registVo.getPhone());
        }else{
            return R.error(15002," 改手机号已注册");
        }
        String password = registVo.getPassword();
        password= DigestUtils.md5DigestAsHex(password.getBytes()); //进行MD5码加密
        memberEntity.setPassword(password);
        memberEntity.setNickname(registVo.getUserName());
        this.save(memberEntity);
        return R.ok();
    }

    @Override
    public boolean chickEmailUnique(String email) {
        LambdaQueryWrapper<MemberEntity> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(MemberEntity::getEmail,email);
        MemberEntity one = this.getOne(wrapper);
        if(one!=null){
            return false;
        }
        return true;
    }

    @Override
    public boolean chickPhoneUnique(String phone) {
        LambdaQueryWrapper<MemberEntity> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(MemberEntity::getMobile,phone);
        MemberEntity one = this.getOne(wrapper);
        if(one!=null){
            return false;
        }
        return true;
    }

    @Override
    public boolean chickUserNamenique(String userName) {
        LambdaQueryWrapper<MemberEntity> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(MemberEntity::getUsername,userName);
        MemberEntity one = this.getOne(wrapper);
        if(one!=null){
            return false;
        }
        return true;
    }

    @Override
    public MemberEntity getByUserName(String userName) {
        LambdaQueryWrapper<MemberEntity> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(MemberEntity::getUsername,userName);
        MemberEntity memberEntity = baseMapper.selectOne(wrapper);

        return memberEntity;
    }

    @Override
    public R login(MemberLoginVo loginVo) {
        LambdaQueryWrapper<MemberEntity> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(MemberEntity::getUsername,loginVo.getUserName());

        MemberEntity member = this.getOne(wrapper);

        if(member==null){
           return R.error(15003,"用户名不存在");
        }
        String password= loginVo.getPassword();
        password= DigestUtils.md5DigestAsHex(password.getBytes()); //进行MD5码加密

        if(password.equals(member.getPassword())){
            return R.ok().put("data",member);
        }else {
            return R.error(15004,"密码错误");
        }

    }

    @Override
    public MemberEntity login(SocialUser socialUser) {

        String uuId=socialUser.getUid();
        //1. 判断当前社交用户是否登录过
        LambdaQueryWrapper<MemberEntity> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(MemberEntity::getSocialUid,uuId);
        MemberEntity one = this.getOne(wrapper);

        if(one!=null){
            //2. 有,更新令牌信息，token
            one.setAccessToken(socialUser.getAccess_token());
            one.setExpiresIn(String.valueOf(socialUser.getExpires_in()));

            this.updateById(one);
            return one;
        }else {
            //1. 没有,注册
            //1.1查询社交用户信息
            try {

                Map<String,String> queryMap=new HashMap<>();
                queryMap.put("access_token",socialUser.getAccess_token());
                queryMap.put("uid",socialUser.getUid());

                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json",
                        "get", new HashMap<String, String>(), queryMap);

                if(response.getStatusLine().getStatusCode()==200){
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    System.out.println("__________---------"+json);
                    JSONObject jsonObject = JSONObject.parseObject(json);

                    //昵称
                    String name = jsonObject.getString("name");
                    //性别
                    String gender = jsonObject.getString("gender");

                    MemberEntity member = new MemberEntity();
                    member.setNickname(name);
                    member.setGender("m".equals(gender)?1:0);
                    member.setAccessToken(socialUser.getAccess_token());
                    member.setExpiresIn(String.valueOf(socialUser.getExpires_in()));
                    member.setSocialUid(uuId);

                    this.save(member);

                    return member;
                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            }


        }



        return null;
    }

}